/**
 * Appointment Calendar Module
 * Handles calendar rendering and date-based appointment management
 */
const AppointmentCalendar = (function() {
    // Calendar state
    let state = {
        currentDate: new Date(),
        selectedDate: new Date(),
        appointments: []
    };

    /**
     * Render the calendar for the current month
     */
    function renderCalendar() {
        const calendarDays = document.getElementById('calendar-days');
        if (!calendarDays) return;
        
        calendarDays.innerHTML = '';
        
        // Update month display
        const monthYearDisplay = document.getElementById('calendar-month');
        if (monthYearDisplay) {
            const options = { year: 'numeric', month: 'long' };
            monthYearDisplay.textContent = state.currentDate.toLocaleDateString('zh-CN', options);
        }
        
        // Get first day of month and number of days
        const firstDay = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), 1);
        const lastDay = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth() + 1, 0);
        
        // Get the starting day of the week (0 = Sunday)
        const startDayOfWeek = firstDay.getDay();
        
        // Generate previous month's days
        const prevMonthLastDay = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), 0).getDate();
        for (let i = startDayOfWeek - 1; i >= 0; i--) {
            const dayElement = createDayElement(prevMonthLastDay - i, true);
            calendarDays.appendChild(dayElement);
        }
        
        // Generate current month's days
        const today = new Date();
        for (let i = 1; i <= lastDay.getDate(); i++) {
            const isToday = today.getDate() === i && 
                            today.getMonth() === state.currentDate.getMonth() && 
                            today.getFullYear() === state.currentDate.getFullYear();
            
            const isSelected = state.selectedDate.getDate() === i && 
                              state.selectedDate.getMonth() === state.currentDate.getMonth() && 
                              state.selectedDate.getFullYear() === state.currentDate.getFullYear();
            
            const dateForAppointmentCheck = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), i);
            const hasAppointments = checkForAppointments(dateForAppointmentCheck);
            
            const dayElement = createDayElement(i, false, isToday, isSelected, hasAppointments);
            calendarDays.appendChild(dayElement);
        }
        
        // Fill the remaining slots with next month's days
        const totalDaysDisplayed = startDayOfWeek + lastDay.getDate();
        const remainingSlots = 42 - totalDaysDisplayed; // 6 rows x 7 days = 42
        
        for (let i = 1; i <= remainingSlots; i++) {
            const dayElement = createDayElement(i, true);
            calendarDays.appendChild(dayElement);
        }
    }
    
    /**
     * Create a day element for the calendar
     */
    function createDayElement(day, isOtherMonth, isToday = false, isSelected = false, hasAppointments = false) {
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day';
        
        if (isOtherMonth) {
            dayElement.classList.add('other-month');
        }
        
        if (isToday) {
            dayElement.classList.add('today');
        }
        
        if (isSelected) {
            dayElement.classList.add('selected');
        }
        
        if (hasAppointments) {
            dayElement.classList.add('has-appointments');
        }
        
        const dayNumber = document.createElement('div');
        dayNumber.className = 'day-number';
        dayNumber.textContent = day;
        dayElement.appendChild(dayNumber);
        
        // Add appointment indicators if there are appointments
        if (hasAppointments && !isOtherMonth) {
            const appointmentStatus = getAppointmentStatusForDay(day);
            if (appointmentStatus.confirmed || appointmentStatus.pending) {
                const dotContainer = document.createElement('div');
                dotContainer.className = 'appointment-dot-container';
                
                if (appointmentStatus.confirmed) {
                    const confirmedDot = document.createElement('div');
                    confirmedDot.className = 'appointment-dot confirmed';
                    dotContainer.appendChild(confirmedDot);
                }
                
                if (appointmentStatus.pending) {
                    const pendingDot = document.createElement('div');
                    pendingDot.className = 'appointment-dot pending';
                    dotContainer.appendChild(pendingDot);
                }
                
                dayElement.appendChild(dotContainer);
            }
        }
        
        // Add click event only for current month days
        if (!isOtherMonth) {
            dayElement.addEventListener('click', () => {
                // Deselect the previously selected day
                document.querySelector('.calendar-day.selected')?.classList.remove('selected');
                
                // Select this day
                dayElement.classList.add('selected');
                
                // Update the selected date
                state.selectedDate = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth(), day);
                
                // Show appointments for the selected date
                showAppointmentsForDate(state.selectedDate);
            });
        }
        
        return dayElement;
    }
    
    /**
     * Navigate to the previous or next month
     */
    function navigateMonth(direction) {
        state.currentDate = new Date(state.currentDate.getFullYear(), state.currentDate.getMonth() + direction, 1);
        renderCalendar();
    }
    
    /**
     * Check if a given date has any appointments
     */
    function checkForAppointments(date) {
        const dateString = date.toISOString().split('T')[0]; // Format: YYYY-MM-DD
        return state.appointments.some(appointment => appointment.date === dateString);
    }
    
    /**
     * Get appointment status counts for a specific day
     */
    function getAppointmentStatusForDay(day) {
        const dateString = new Date(
            state.currentDate.getFullYear(), 
            state.currentDate.getMonth(), 
            day
        ).toISOString().split('T')[0];
        
        const appointmentsForDay = state.appointments.filter(appointment => appointment.date === dateString);
        
        return {
            confirmed: appointmentsForDay.some(appointment => appointment.status === 'CONFIRMED'),
            pending: appointmentsForDay.some(appointment => appointment.status === 'PENDING')
        };
    }
    
    /**
     * Show appointments for a selected date
     */
    function showAppointmentsForDate(date) {
        const selectedDateElem = document.getElementById('selected-date');
        const appointmentsContainer = document.getElementById('selected-date-appointments');
        
        if (!selectedDateElem || !appointmentsContainer) return;
        
        // Format the date
        const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
        selectedDateElem.textContent = date.toLocaleDateString('zh-CN', options);
        
        // Get appointments for this date
        const dateString = date.toISOString().split('T')[0];
        const appointmentsForDay = state.appointments.filter(appointment => appointment.date === dateString);
        
        // Clear the container
        appointmentsContainer.innerHTML = '';
        
        if (appointmentsForDay.length === 0) {
            // Show empty state
            appointmentsContainer.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-calendar-day"></i>
                    <p>当前日期没有预约</p>
                    <button id="create-appointment-for-date" class="btn btn-primary">
                        <i class="fas fa-plus"></i> 创建预约
                    </button>
                </div>
            `;
            
            // Add event listener to the create button
            const createBtn = document.getElementById('create-appointment-for-date');
            if (createBtn) {
                createBtn.addEventListener('click', () => {
                    // Call the create appointment function with the selected date
                    if (typeof AppointmentManager !== 'undefined' && AppointmentManager.showCreateModal) {
                        AppointmentManager.showCreateModal(date);
                    }
                });
            }
        } else {
            // Sort appointments by time
            appointmentsForDay.sort((a, b) => a.time.localeCompare(b.time));
            
            // Create appointment elements
            appointmentsForDay.forEach(appointment => {
                const appointmentElem = createAppointmentElement(appointment);
                appointmentsContainer.appendChild(appointmentElem);
            });
        }
    }
    
    /**
     * Create an appointment element for the selected date view
     */
    function createAppointmentElement(appointment) {
        const appointmentElem = document.createElement('div');
        appointmentElem.className = `day-appointment ${appointment.status.toLowerCase()}`;
        
        // Format the time
        const timeDisplay = formatAppointmentTime(appointment.time, appointment.duration);
        
        appointmentElem.innerHTML = `
            <span class="status-badge ${appointment.status.toLowerCase()}">${getStatusText(appointment.status)}</span>
            <div class="appointment-time">${timeDisplay}</div>
            <div class="appointment-doctor">
                <img src="${appointment.doctorAvatar}" alt="${appointment.doctorName}">
                <div>
                    <div class="doctor-name">${appointment.doctorName}</div>
                    <div class="doctor-specialty">${appointment.doctorSpecialty}</div>
                </div>
            </div>
            <div class="appointment-details">
                <div class="appointment-type">
                    <i class="fas fa-clipboard-list"></i> ${getAppointmentTypeText(appointment.type)}
                </div>
                <div class="appointment-location">
                    <i class="fas fa-map-marker-alt"></i> ${appointment.location}
                </div>
            </div>
            ${appointment.notes ? `<div class="appointment-notes">${appointment.notes}</div>` : ''}
            <div class="appointment-actions">
                ${appointment.status === 'PENDING' || appointment.status === 'CONFIRMED' ? 
                `<button class="btn btn-sm btn-outline-danger" data-action="cancel" data-id="${appointment.id}">取消预约</button>` : ''}
                ${appointment.status === 'CONFIRMED' ? 
                `<button class="btn btn-sm btn-primary" data-action="start-consultation" data-id="${appointment.id}">开始问诊</button>` : ''}
                ${appointment.status === 'COMPLETED' ? 
                `<button class="btn btn-sm btn-outline" data-action="view-record" data-id="${appointment.id}">查看记录</button>` : ''}
            </div>
        `;
        
        // Add event listeners to the buttons
        const buttons = appointmentElem.querySelectorAll('button[data-action]');
        buttons.forEach(button => {
            button.addEventListener('click', (e) => {
                const action = button.dataset.action;
                const appointmentId = button.dataset.id;
                
                if (action === 'cancel') {
                    if (typeof AppointmentManager !== 'undefined' && AppointmentManager.cancelAppointment) {
                        AppointmentManager.cancelAppointment(appointmentId);
                    }
                } else if (action === 'start-consultation') {
                    if (typeof AppointmentManager !== 'undefined' && AppointmentManager.startConsultation) {
                        AppointmentManager.startConsultation(appointmentId);
                    }
                } else if (action === 'view-record') {
                    if (typeof AppointmentManager !== 'undefined' && AppointmentManager.viewRecord) {
                        AppointmentManager.viewRecord(appointmentId);
                    }
                }
            });
        });
        
        return appointmentElem;
    }
    
    /**
     * Format the appointment time with duration
     */
    function formatAppointmentTime(time, duration) {
        const [hours, minutes] = time.split(':');
        const startTime = `${hours}:${minutes}`;
        
        // Calculate end time
        const endTime = calculateEndTime(time, duration);
        
        return `${startTime} - ${endTime}`;
    }
    
    /**
     * Calculate the end time based on start time and duration
     */
    function calculateEndTime(startTime, durationMinutes) {
        const [hours, minutes] = startTime.split(':').map(Number);
        
        const startDate = new Date();
        startDate.setHours(hours, minutes, 0, 0);
        
        const endDate = new Date(startDate.getTime() + durationMinutes * 60000);
        
        return endDate.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false });
    }
    
    /**
     * Get the display text for an appointment status
     */
    function getStatusText(status) {
        const statusMap = {
            'PENDING': '待确认',
            'CONFIRMED': '已确认',
            'COMPLETED': '已完成',
            'CANCELLED': '已取消',
            'RESCHEDULED': '已改期'
        };
        
        return statusMap[status] || status;
    }
    
    /**
     * Get the display text for an appointment type
     */
    function getAppointmentTypeText(type) {
        const typeMap = {
            'REGULAR': '常规问诊',
            'FOLLOW_UP': '复诊',
            'CONSULTATION': '专家会诊',
            'PHYSICAL': '体检预约',
            'EMERGENCY': '紧急预约'
        };
        
        return typeMap[type] || type;
    }
    
    /**
     * Set appointments data and re-render
     */
    function setAppointments(appointments) {
        state.appointments = appointments;
        renderCalendar();
        showAppointmentsForDate(state.selectedDate);
    }
    
    /**
     * Set the current selected date
     */
    function setSelectedDate(date) {
        state.selectedDate = new Date(date);
        state.currentDate = new Date(date.getFullYear(), date.getMonth(), 1);
        renderCalendar();
        showAppointmentsForDate(state.selectedDate);
    }
    
    /**
     * Initialize the calendar
     */
    function init() {
        // Set up event listeners for the calendar navigation
        const prevMonthBtn = document.getElementById('prev-month');
        const nextMonthBtn = document.getElementById('next-month');
        
        if (prevMonthBtn) {
            prevMonthBtn.addEventListener('click', () => navigateMonth(-1));
        }
        
        if (nextMonthBtn) {
            nextMonthBtn.addEventListener('click', () => navigateMonth(1));
        }
        
        // Initial render
        renderCalendar();
        showAppointmentsForDate(state.selectedDate);
    }
    
    // Public API
    return {
        init: init,
        setAppointments: setAppointments,
        setSelectedDate: setSelectedDate,
        renderCalendar: renderCalendar
    };
})(); 